package br.ufrn.cerescaico.sepe.email;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Universidade Estadual da Paraíba
 * Cidade: Monteiro - Paraíba
 *
 * @author  Ana Emília Victor Barbosa, anaemiliabarbosa@gmail.com <br>
 * @version 1.0 <br>
 *
 * Copyright (C) 2008
 */
public class MailManager {

	private final String usuario = "sepe.ufrn";
	private final String senha = "ufrnsepe2010";
	private final String from_mail="sepe.ufrn@gmail.com";
		
	private static final String SMTP_HOST_NAME = "smtp.gmail.com";
	private static final String SMTP_PORT = "465";
	private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
	

	public MailManager() {
	}

	public void send(MailMessage msg) throws Exception {
		try {
			Properties mailProps = new Properties();
			mailProps.put("mail.smtp.host", SMTP_HOST_NAME);
			
			SimpleAuth auth = null;
			auth = new SimpleAuth(usuario, senha);
			
			mailProps.put("mail.smtp.auth", "true");
			mailProps.put("mail.user", usuario);
			mailProps.put("mail.from", msg.getFrom());
			mailProps.put("mail.to", msg.getTo());

			mailProps.put("mail.smtp.host", SMTP_HOST_NAME);
			mailProps.put("mail.smtp.auth", "true");
			mailProps.put("mail.debug", "true");

			mailProps.put("mail.smtp.port", SMTP_PORT);
			mailProps.put("mail.smtp.socketFactory.port", SMTP_PORT);
			mailProps.put("mail.smtp.socketFactory.class", SSL_FACTORY);
			mailProps.put("mail.smtp.socketFactory.fallback", "false");
			
			Session mailSession = Session.getDefaultInstance(mailProps, auth);
			
			mailSession.setDebug(true);
			Message email = new MimeMessage(mailSession);
			email.setRecipients(Message.RecipientType.TO, InternetAddress
					.parse(msg.getTo()));
			if (!msg.getCc().trim().equals("")) {
				email.setRecipients(Message.RecipientType.CC, InternetAddress
						.parse(msg.getCc()));
			}
			if (!msg.getBcc().trim().equals("")) {
				email.setRecipients(Message.RecipientType.BCC, InternetAddress
						.parse(msg.getBcc()));
			}
			email.setFrom(new InternetAddress(from_mail));
			email.setSubject(msg.getSubject());
			email.setContent(msg.getText(), "text/plain");
			Transport tr = mailSession.getTransport("smtp");
			tr.connect(SMTP_HOST_NAME, usuario, senha);
			email.saveChanges(); // don't forget this
			tr.sendMessage(email, email.getAllRecipients());
			tr.close();

		} catch (Exception e) {
			System.out.println(" [E] ERROR: " + e);
			e.printStackTrace(System.out);
			throw e;
		}
		System.out.println(" [#] Email successfully sent");
		return;
	}

	public void send(String to, String cc, String bcc, String from,
			String subject, String text) throws Exception {
		MailMessage msg = new MailMessage(to, cc, bcc, from, subject, text);
		this.send(msg);
		return;
	}

}